package com.chlitina.store.modules.cash.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.utils.DataFormater;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.common.utils.StoreProductUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreCardTemplateAll;
import com.chlitina.store.modules.base.entity.StoreCardTemplateDuration;
import com.chlitina.store.modules.base.entity.StoreCardTemplateProduct;
import com.chlitina.store.modules.base.entity.StoreCardTemplateProductDetail;
import com.chlitina.store.modules.base.entity.StoreCardTemplateTimes;
import com.chlitina.store.modules.base.entity.StoreCare;
import com.chlitina.store.modules.cash.dao.StoreCardAllDao;
import com.chlitina.store.modules.cash.dao.StoreCardDurationDao;
import com.chlitina.store.modules.cash.dao.StoreCardProductDao;
import com.chlitina.store.modules.cash.dao.StoreCardTimesDao;
import com.chlitina.store.modules.cash.entity.StoreCardAll;
import com.chlitina.store.modules.cash.entity.StoreCardDuration;
import com.chlitina.store.modules.cash.entity.StoreCardProduct;
import com.chlitina.store.modules.cash.entity.StoreCardTimes;
import com.chlitina.store.modules.cash.model.CardAllForm;
import com.chlitina.store.modules.cash.model.CardDurationForm;
import com.chlitina.store.modules.cash.model.CardProductForm;
import com.chlitina.store.modules.cash.model.CardTimesForm;
import com.chlitina.store.modules.cash.model.Member;
import com.chlitina.store.modules.employee.dao.EmployeeDao;
import com.chlitina.store.modules.sys.utils.StoreUtils;

@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/cash/oldcard")
public class AddOldCardController extends BaseController {
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private StoreCardTimesDao storeCardTimesDao;
	@Autowired
	private StoreCardProductDao storeCardProductDao;
	@Autowired
	private StoreCardDurationDao storeCardDurationDao;
	@Autowired
	private StoreCardAllDao storeCardAllDao;
	
	public static interface KEY {
		String KEY_MEMBER = "member";
		String KEY_MESSAGE = "message";
	}

	static String addSuccess ="老会员卡添加成功";
	
	public static interface URI {
		String URI_MEMBER_ADD_CARD_TIMES_PAGE = "modules/cash/memberAddCardTimes";
		String URI_MEMBER_ADD_CARD_DURATION_PAGE = "modules/cash/memberAddCardDuration";
		String URI_MEMBER_ADD_CARD_PRODUCT_PAGE = "modules/cash/memberAddCardProduct";
		String URI_MEMBER_ADD_CARD_ALL_PAGE = "modules/cash/memberAddCardAll";

		String URI_MEMBER_ADD_CARD_TIMES_FORM = "modules/cash/addCardTimesForm";
		String URI_MEMBER_ADD_CARD_DURATION_FORM = "modules/cash/addCardDurationForm";
		String URI_MEMBER_ADD_CARD_PRODUCT_FORM = "modules/cash/addCardProductForm";
		String URI_MEMBER_ADD_CARD_ALL_FORM = "modules/cash/addCardAllForm";
	}

	String getDirectURL(String uri) {
		return "redirect:" + Global.ADMIN_PATH + "/cash/oldcard/" + uri;
	}

	@RequestMapping(value = { "cards/add" })
	public String newCards(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		return URI.URI_MEMBER_ADD_CARD_TIMES_PAGE;
	}

	@RequestMapping(value = { "cards/add/cardTimesPage" })
	public String newCardTimesPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		return URI.URI_MEMBER_ADD_CARD_TIMES_PAGE;
	}

	@RequestMapping(value = { "cards/add/cardDurationPage" })
	public String newCardDurationPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		return URI.URI_MEMBER_ADD_CARD_DURATION_PAGE;
	}

	@RequestMapping(value = { "cards/add/cardProductPage" })
	public String newCardProductPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		return URI.URI_MEMBER_ADD_CARD_PRODUCT_PAGE;
	}

	@RequestMapping(value = { "cards/add/cardAllPage" })
	public String newCardAllPage(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Member member = getMember();
		if (member == null) {
			model.addAttribute("message", "会员状态丢失");
			return MemberController.MEMBER_URL;
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		return URI.URI_MEMBER_ADD_CARD_ALL_PAGE;
	}

	@RequestMapping(value = { "cards/add/cardTimesForm" })
	public String newCardTimesForm(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER,
				request.getSession().getAttribute(KEY.KEY_MEMBER));

		String cardID = request.getParameter("cardID");
		StoreCardTemplateTimes template = member.getNewCards()
				.getStoreCardTemplateTimesById(Long.parseLong(cardID));

		if (template == null) {
			addMessage(redirectAttributes, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardTimesPage");
		}
		CardTimesForm cardForm = new CardTimesForm();
		cardForm.setMemberID(member.getCustomer().getId());
		cardForm.setTemplateID(template.getId());
		cardForm.setCardName(template.getName());
		cardForm.setCardTimes(template.getTimes());
		StoreCare storeCare = template.getStoreCare();
		if (storeCare.getCare_type() == StoreCare.TYPE_SELF) {
			cardForm.setCareDuration(storeCare.getStoreSelfCare().getDuration());
			cardForm.setCareName(storeCare.getStoreSelfCare().getName());
		} else {
			cardForm.setCareDuration(storeCare.getCare().getDuration());
			cardForm.setCareName(storeCare.getCare().getName());
		}
		cardForm.setRetailPrice(template.getRetail_price());
		cardForm.setRealCost(template.getReal_cost());
		model.addAttribute("cardForm", cardForm);
		return URI.URI_MEMBER_ADD_CARD_TIMES_FORM;
	}

	@RequestMapping(value = { "cards/add/cardTimes" })
	public String newCardTimes(CardTimesForm cardForm,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		if (cardForm.getMemberID() != member.getCustomer().getId()) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}

		model.addAttribute(KEY.KEY_MEMBER,
				request.getSession().getAttribute(KEY.KEY_MEMBER));

		StoreCardTemplateTimes template = member.getNewCards()
				.getStoreCardTemplateTimesById(cardForm.getTemplateID());

		if (template == null) {
			addMessage(redirectAttributes, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardTimesPage");
		}

		String retailPrice = request.getParameter("retailPrice");
		float parseFloat = Float.parseFloat(retailPrice);
	 
		StoreCardTimes card = new StoreCardTimes();
		card.setCardNumber(ConsumeUtils.generateCardNumberForCard(card));
		card.setBeginTime(new Date());
		card.setCustomer(member.getCustomer());
		card.setNewCardTimes(cardForm.getCardTimes());
		card.setRemainMoney(parseFloat);
		card.setRemainTimes(cardForm.getCardTimes());
		card.setTemplate(template);
		card.setStore(StoreUtils.getStore());
		card.setCostPerTime(DataFormater.formatMoneyFloat(card.getRemainMoney()
				/ card.getRemainTimes()));
		storeCardTimesDao.save(card);
		member.addOldCard(card);
		addMessage(redirectAttributes, addSuccess);
		return getDirectURL("cards/add/cardTimesPage");
	}

	boolean contains(List<Long> added, Long id) {
		for (Long value : added) {
			if (value.longValue() == id.longValue()) {
				return true;
			}
		}
		return false;
	}

	@RequestMapping(value = { "cards/add/cardAllForm" })
	public String newCardAllForm(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER,
				request.getSession().getAttribute(KEY.KEY_MEMBER));

		String cardID = request.getParameter("cardID");
		StoreCardTemplateAll template = member.getNewCards()
				.getStoreCardTemplateAllById(Long.parseLong(cardID));

		if (template == null) {
			addMessage(redirectAttributes, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardAllPage");
		}
		CardAllForm cardForm = new CardAllForm();
		cardForm.setMemberID(member.getCustomer().getId());
		cardForm.setTemplateID(template.getId());
		cardForm.setCardName(template.getName());
		cardForm.setCareDiscount(template.getCare_discount() * 100);
		cardForm.setProductDiscount(template.getProduct_discount() * 100);

		cardForm.setRetailPrice(template.getRetail_price());
		cardForm.setRealCost(template.getReal_cost());
		model.addAttribute("cardForm", cardForm);
		return URI.URI_MEMBER_ADD_CARD_ALL_FORM;
	}

	@RequestMapping(value = { "cards/add/cardAllDelete" })
	public String deteleCardAll(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		String cardID = request.getParameter("cardID");

		if (cardID == null) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardAllPage");
		}
		int parseInt = 0;
		try {
			parseInt = Integer.parseInt(cardID);
		} catch (NumberFormatException e) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardAllPage");
		}
		boolean result = member.dropOpenCardAll(parseInt);
		addMessage(redirectAttributes, "移除成功");
		member.updateMenuState();
		return getDirectURL("cards/add/cardAllPage");
	}

	@RequestMapping(value = { "cards/add/cardProductDelete" })
	public String deteleCardProduct(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		String cardID = request.getParameter("cardID");

		if (cardID == null) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardProductPage");
		}
		int parseInt = 0;
		try {
			parseInt = Integer.parseInt(cardID);
		} catch (NumberFormatException e) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardProductPage");
		}
		boolean result = member.dropOpenCardProduct(parseInt);
		addMessage(redirectAttributes, "移除成功");
		member.updateMenuState();
		return getDirectURL("cards/add/cardProductPage");
	}

	@RequestMapping(value = { "cards/add/cardTimesDelete" })
	public String deteleCardTimes(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		String cardID = request.getParameter("cardID");

		if (cardID == null) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardTimesPage");
		}
		int parseInt = 0;
		try {
			parseInt = Integer.parseInt(cardID);
		} catch (NumberFormatException e) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardTimesPage");
		}
		boolean result = member.dropOpenCardTimes(parseInt);
		addMessage(redirectAttributes, "移除成功");
		member.updateMenuState();
		return getDirectURL("cards/add/cardTimesPage");
	}

	@RequestMapping(value = { "cards/add/cardDurationDelete" })
	public String deteleCardDurarion(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);
		String cardID = request.getParameter("cardID");

		if (cardID == null) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardDurationPage");
		}
		int parseInt = 0;
		try {
			parseInt = Integer.parseInt(cardID);
		} catch (NumberFormatException e) {
			addMessage(redirectAttributes, "错误的会员卡编号");
			return getDirectURL("cards/add/cardDurationPage");
		}
		boolean result = member.dropOpenCardDuration(parseInt);
		addMessage(redirectAttributes, "移除成功");
		member.updateMenuState();
		return getDirectURL("cards/add/cardDurationPage");
	}

	@RequestMapping(value = { "cards/add/cardAll" })
	public String newCardAll(CardAllForm cardForm, HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);

		StoreCardTemplateAll template = member.getNewCards()
				.getStoreCardTemplateAllById(cardForm.getTemplateID());
		if (template == null) {
			addMessage(redirectAttributes, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardAllPage");
		}
		 
		StoreCardAll card = new StoreCardAll();
		card.setStore(StoreUtils.getStore());
		card.setBeginTime(new Date());
		card.setTemplate(template);
		card.setCareDiscount(cardForm.getCareDiscount() / 100);
		card.setProductDiscount(cardForm.getProductDiscount() / 100);
		card.setCardNumber(ConsumeUtils.generateCardNumberForCard(card));
		card.setCustomer(member.getCustomer());
		card.setMoney(cardForm.getRetailPrice());
		storeCardAllDao.save(card);
		member.addOldCard(card);

		addMessage(redirectAttributes, addSuccess);
		return getDirectURL("cards/add/cardAllPage");
	}

	private Member getMember() {
		return StoreUtils.getMember();
	}

	@RequestMapping(value = { "cards/add/cardDurationForm" })
	public String newCardDurationForm(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER,
				request.getSession().getAttribute(KEY.KEY_MEMBER));

		String cardID = request.getParameter("cardID");
		StoreCardTemplateDuration template = member.getNewCards()
				.getStoreCardTemplateDurationById(Long.parseLong(cardID));

		if (template == null) {
			addMessage(redirectAttributes, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardDurationPage");
		}
		CardDurationForm cardForm = new CardDurationForm();
		cardForm.setMemberID(member.getCustomer().getId());
		cardForm.setTemplateID(template.getId());
		cardForm.setCardName(template.getName());
		cardForm.setCardDuration(template.getDuration());
		StoreCare storeCare = template.getStoreCare();
		if (storeCare.getCare_type() == StoreCare.TYPE_SELF) {
			cardForm.setCareDuration(storeCare.getStoreSelfCare().getDuration());
			cardForm.setCareName(storeCare.getStoreSelfCare().getName());
		} else {
			cardForm.setCareDuration(storeCare.getCare().getDuration());
			cardForm.setCareName(storeCare.getCare().getName());
		}
		cardForm.setRetailPrice(template.getRetail_price());
		cardForm.setRealCost(template.getReal_cost());
		model.addAttribute("cardForm", cardForm);
		return URI.URI_MEMBER_ADD_CARD_DURATION_FORM;
	}

	@RequestMapping(value = { "cards/add/cardDuration" })
	public String newCardDuration(CardDurationForm cardForm,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {

		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		if (cardForm.getMemberID() != member.getCustomer().getId()) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}

		model.addAttribute(KEY.KEY_MEMBER,
				request.getSession().getAttribute(KEY.KEY_MEMBER));

		StoreCardTemplateDuration template = member.getNewCards()
				.getStoreCardTemplateDurationById(cardForm.getTemplateID());

		if (template == null) {
			model.addAttribute(KEY.KEY_MESSAGE, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardDurationPage");
		}

		Date endDate = cardForm.getEndDate();
		StoreCardDuration card = new StoreCardDuration();
		card.setCardNumber(ConsumeUtils.generateCardNumberForCard(card));
		card.setBeginTime(DateUtils.calculateDurationStartDay(endDate,cardForm.getCardDuration()));
		card.setEndTime(DateUtils.getEndOfDay(endDate));
		card.setCustomer(member.getCustomer());
		card.setTemplate(template);
		card.setStore(StoreUtils.getStore());
		storeCardDurationDao.save(card);
		member.addOldCard(card);
		addMessage(redirectAttributes, addSuccess);
		return getDirectURL("cards/add/cardDurationPage");
	}

	@RequestMapping(value = { "cards/add/cardProductForm" })
	public String newCardProductForm(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER,
				request.getSession().getAttribute(KEY.KEY_MEMBER));

		String cardID = request.getParameter("cardID");
		StoreCardTemplateProduct template = member.getNewCards()
				.getStoreCardTemplateProductById(Long.parseLong(cardID));

		if (template == null) {
			addMessage(redirectAttributes, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardProductPage");
		}
		CardProductForm cardForm = new CardProductForm();
		cardForm.setMemberID(member.getCustomer().getId());
		cardForm.setTemplateID(template.getId());
		cardForm.setCardName(template.getName());
		List<StoreCardTemplateProductDetail> productList = template
				.getProductList();
		List<String> products = cardForm.getProducts();
		for (StoreCardTemplateProductDetail detail : productList) {
			products.add(StoreProductUtils.getName(detail.getStoreProduct()));
		}
		cardForm.setProductDiscount(template.getDiscount() * 100);
		cardForm.setRetailPrice(template.getRetail_price());
		cardForm.setRealCost(template.getReal_cost());
		model.addAttribute("cardForm", cardForm);
		return URI.URI_MEMBER_ADD_CARD_PRODUCT_FORM;
	}

	@RequestMapping(value = { "cards/add/cardProduct" })
	public String newCardProduct(CardProductForm cardForm,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {
		Member member = getMember();
		if (member == null) {
			addMessage(redirectAttributes, "会员状态丢失");
			return getDirectURL("");
		}
		model.addAttribute(KEY.KEY_MEMBER, member);

		StoreCardTemplateProduct template = member.getNewCards()
				.getStoreCardTemplateProductById(cardForm.getTemplateID());
		if (template == null) {
			addMessage(redirectAttributes, "添加失败，获取会员卡模板失败");
			return getDirectURL("cards/add/cardProductPage");
		}
      
		
		String retailPrice = request.getParameter("retailPrice");
		float parseFloat = Float.parseFloat(retailPrice);
		
		StoreCardProduct card = new StoreCardProduct();
		card.setStore(StoreUtils.getStore());
		card.setBeginTime(new Date());
		card.setTemplate(template);
		card.setMoney(parseFloat);
		card.setCustomer(member.getCustomer());
		card.setProductDiscount(cardForm.getProductDiscount() / 100);
		card.setCardNumber(ConsumeUtils.generateCardNumberForCard(card));
		storeCardProductDao.save(card);
		member.addOldCard(card);
		addMessage(redirectAttributes, addSuccess);
		return getDirectURL("cards/add/cardProductPage");
	}
}
